// frontend/src/main.js
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
import { CONFIG } from './config.js';
import { ApiClient } from './utils/api.js';
import { components } from './components/components.js';

const App = {
  data() {
    return {
      currentPage: 'welcome', // welcome, login, register, dashboard, admin
      selectedPlatform: null, // biocloud, health
      user: null,
      message: '',
      messageType: 'info', // success, error, info, warning
      dashboard: {
        activeTab: 'overview' // overview, projects, tasks, profile, admin
      },
      admin: {
        activeTab: 'users', // users, projects, userProjects, samples
        users: [],
        projects: [],
        userProjects: [],
        samples: [],
        selectedUserProject: null
      }
    };
  },
  
  computed: {
    platformTitle() {
      if (this.selectedPlatform === 'biocloud') {
        return '库美生物云平台';
      } else if (this.selectedPlatform === 'health') {
        return '库美大健康平台';
      }
      return '';
    },
    
    // 计算当前平台的主题颜色
    platformThemeClass() {
      return this.selectedPlatform === 'biocloud' ? 'bg-primary' : 'bg-success';
    },
    
    // 计算当前平台的按钮颜色
    platformButtonClass() {
      return this.selectedPlatform === 'biocloud' ? 'btn-primary' : 'btn-success';
    },
    
    // 判断是否显示注册按钮
    showRegisterButton() {
      // 大健康平台不显示注册按钮，只能由管理员添加
      return this.selectedPlatform !== 'health';
    }
  },
  
  methods: {
    // 检查用户登录状态
    checkAuthStatus() {
        const token = localStorage.getItem('token');
        console.log('检查认证状态，token:', token);
        if (token && !this.user) {
            console.log('有token但无用户信息，获取用户资料');
            this.fetchUserProfile(token);
        } else if (!token && this.user) {
            console.log('无token但有用户信息，清除用户状态');
            this.user = null;
            this.setMessage('认证信息已过期，请重新登录', 'warning');
        } else if (!token && !this.user) {
            console.log('未登录状态');
        } else {
            console.log('已登录状态，用户:', this.user.username);
        }
    },
    
    async fetchUserProfile(token) {
        try {
            const { ok, data } = await ApiClient.fetchUserData(token);
            if (ok) {
                this.user = data;
            } else {
                // 如果获取用户信息失败，清除token
                localStorage.removeItem('token');
                this.user = null;
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            localStorage.removeItem('token');
            this.user = null;
        }
    },
    
    // 在应用启动时检查认证状态
    mounted() {
        this.checkAuthStatus();
    },
    showWelcome() {
      // 如果用户已登录，跳转到仪表板而不是欢迎页面
      if (this.user) {
        this.currentPage = 'dashboard';
        this.dashboard.activeTab = 'overview';
      } else {
        this.currentPage = 'welcome';
        this.selectedPlatform = null;
      }
      this.message = '';
    },
    
    selectPlatform(platform) {
      this.selectedPlatform = platform;
      this.currentPage = 'login';
      this.message = '';
    },
    
    showLogin() {
      this.currentPage = 'login';
      this.message = '';
    },
    
    showRegister() {
      this.currentPage = 'register';
      this.message = '';
    },
    
    setMessage(text, type = 'info') {
      this.message = text;
      this.messageType = type;
    },
    
    clearMessage() {
      this.message = '';
    },
    async handleLogin(identifier, password) {
      console.log('尝试登录:', identifier);
      const { ok, data } = await ApiClient.login(identifier, password);
      
      if (ok) {
        console.log('登录成功，设置token:', data.access_token);
        localStorage.setItem('token', data.access_token);
        this.user = data.user;
        console.log('当前用户:', this.user);
        this.setMessage('登录成功', 'success');
        this.currentPage = 'dashboard';
        this.dashboard.activeTab = 'overview';
      } else {
        console.log('登录失败:', data.message);
        this.setMessage(data.message, 'error');
      }
    },
    
    async handleRegister(username, email, password, platform) {
      const { ok, data } = await ApiClient.register(username, email, password, platform);
      
      if (ok) {
        this.setMessage('注册成功，请登录', 'success');
        this.currentPage = 'login';
      } else {
        this.setMessage(data.message, 'error');
      }
    },
    
    showAdminPanel() {
      this.currentPage = 'admin';
      this.admin.activeTab = 'users';
    },
    
    logout() {
      localStorage.removeItem('token');
      this.user = null;
      this.showWelcome();
      this.setMessage('您已成功退出登录', 'success');
    },
    
    switchDashboardTab(tab) {
      this.dashboard.activeTab = tab;
    },
    
    switchAdminTab(tab) {
      this.admin.activeTab = tab;
    },
    
    // 添加更新用户列表的方法
    updateUsers(users) {
      this.admin.users = users;
    }
  },
  
  components,
  
  template: `
    <div class="min-vh-100 bg-light">
      <!-- 导航栏 -->
      <navbar-component 
        :user="user"
        :selected-platform="selectedPlatform"
        :platform-theme-class="platformThemeClass"
        @show-welcome="showWelcome"
        @show-admin-panel="showAdminPanel"
        @logout="logout"
        @switch-to-profile="() => { currentPage = 'dashboard'; dashboard.activeTab = 'profile'; }">
      </navbar-component>
      
      <!-- 消息提示 -->
      <div class="container mt-3" v-if="message">
        <div class="alert" 
             :class="{
               'alert-success': messageType === 'success',
               'alert-danger': messageType === 'error',
               'alert-info': messageType === 'info',
               'alert-warning': messageType === 'warning'
             }" 
             role="alert">
          <i class="bi" 
             :class="{
               'bi-check-circle': messageType === 'success',
               'bi-exclamation-triangle': messageType === 'warning',
               'bi-info-circle': messageType === 'info',
               'bi-exclamation-circle': messageType === 'error'
             }"></i>
          {{ message }}
          <button type="button" class="btn-close float-end" 
                  @click="clearMessage"></button>
        </div>
      </div>

      <!-- 欢迎页面 -->
      <welcome-component 
        v-if="currentPage === 'welcome'"
        @select-platform="selectPlatform">
      </welcome-component>

      <!-- 登录页面 -->
      <login-component 
        v-if="currentPage === 'login'"
        :selected-platform="selectedPlatform"
        :platform-theme-class="platformThemeClass"
        :platform-button-class="platformButtonClass"
        :show-register-button="showRegisterButton"
        @show-welcome="showWelcome"
        @show-register="showRegister"
        @login="handleLogin">
      </login-component>

      <!-- 注册页面 -->
      <register-component 
        v-if="currentPage === 'register'"
        :selected-platform="selectedPlatform"
        :platform-theme-class="platformThemeClass"
        :platform-button-class="platformButtonClass"
        @show-welcome="showWelcome"
        @show-login="showLogin"
        @set-message="setMessage"
        @register="handleRegister">
      </register-component>

      <!-- 用户首页 dashboard -->
      <dashboard-component 
        v-if="currentPage === 'dashboard'"
        :user="user"
        :dashboard="dashboard"
        :platform-theme-class="platformThemeClass"
        @switch-tab="switchDashboardTab"
        @show-admin-panel="showAdminPanel">
      </dashboard-component>

      <!-- 管理员面板 -->
      <admin-panel-component 
        v-if="currentPage === 'admin'"
        :admin="admin"
        :user="user"
        @show-welcome="showWelcome"
        @switch-tab="switchAdminTab"
        @update-users="updateUsers"
        @set-message="setMessage">
      </admin-panel-component>

      <!-- 页脚 -->
      <footer class="bg-dark text-white py-4 mt-5" v-if="currentPage !== 'welcome'">
        <div class="container">
          <div class="row">
            <div class="col-md-6 mb-3 mb-md-0">
              <h5><i class="bi bi-dna me-2"></i>库美生物信息云平台</h5>
              <p class="text-light">
                提供专业的生物信息学分析服务和健康管理解决方案
              </p>
            </div>
            <div class="col-md-3 mb-3 mb-md-0">
              <h5>平台</h5>
              <ul class="list-unstyled">
                <li><a href="#" class="text-light text-decoration-none" @click="selectPlatform('biocloud')">生物云平台</a></li>
                <li><a href="#" class="text-light text-decoration-none" @click="selectPlatform('health')">大健康平台</a></li>
              </ul>
            </div>
            <div class="col-md-3">
              <h5>支持</h5>
              <ul class="list-unstyled">
                <li><a href="#" class="text-light text-decoration-none">帮助中心</a></li>
                <li><a href="#" class="text-light text-decoration-none">联系我们</a></li>
              </ul>
            </div>
          </div>
          <hr class="my-4 bg-secondary">
          <div class="text-center text-light">
            <p class="mb-0">&copy; 2023 库美生物信息云平台. 保留所有权利.</p>
          </div>
        </div>
      </footer>
    </div>
  `
};

// 添加全局样式
const style = document.createElement('style');
style.innerHTML = `
  .hero-background {
    background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.7)), 
                url('https://images.unsplash.com/photo-1576091160550-2173dba999ef?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80') center/cover no-repeat;
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
  
  .platform-card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
  }
  
  .platform-biocloud-hover {
    transform: translateY(-10px);
    box-shadow: 0 10px 20px rgba(0, 123, 255, 0.3) !important;
  }
  
  .platform-health-hover {
    transform: translateY(-10px);
    box-shadow: 0 10px 20px rgba(40, 167, 69, 0.3) !important;
  }
  
  .platform-icon {
    width: 80px;
    height: 80px;
    transition: transform 0.3s ease;
  }
  
  .platform-card:hover .platform-icon {
    transform: scale(1.1);
  }
  
  @media (max-width: 991.98px) {
    .hero-background {
      display: none;
    }
  }
`;

document.head.appendChild(style);

createApp(App).mount('#app');